$(function () {

  // 选择头像刷新
  $('#inputCover').on('change', function () {
    let file = this.files[0];
    let src = URL.createObjectURL(file);
    $('#coverimg').prop('src', src);
  });

  // 获取动态分类
  $.ajax({
    url: 'http://localhost:8080/api/v1/admin/category/list',
    headers: {
      Authorization: localStorage.getItem('token')
    },
    success: function (res) {
      let html = res.data.reduce((html, value) => html += `<option value=${value.id}>${value.name}</option>`);
      $('#category').html(html);
    }
  })


  // 日期插件
  getLayDate();
  function getLayDate() {
    layui.use('laydate', function () {
      var laydate = layui.laydate;

      //执行一个laydate实例
      laydate.render({
        elem: '#articleDate' //指定元素
      });
    });
  }

  // 富文本编辑器
  getRichText()
  function getRichText() {
    tinymce.init({
      selector: '#articleContent',
      language: 'zh_CN'
    });
  }



  // 发布文章

  function addArticle(statc) {
    console.log(statc);
    let formdata = new FormData($('#form')[0]);
    formdata.append('content', tinyMCE.editors['articleContent'].getContent());
    formdata.append('state', statc);

    /* formdata.forEach(function(value, key) {
      console.log('value：'+value+' key: '+ key);
    }); */

    $.ajax({
      url: 'http://localhost:8080/api/v1/admin/article/publish',
      headers: {
        Authorization: localStorage.getItem('token')
      },
      type: 'post',
      processData: false,
      contentType: false,
      data: formdata,
      success: function (res) {
        location.href = './article_list.html';
      }
    })
  }
  $('.btn-edit').on('click', function() {
    addArticle('已发布');
  });
  $('.btn-draft').on('click', function() {
    addArticle('草稿');
  });


})